package com.example.net.down

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import com.example.baseutils.Constance
import com.example.baseutils.FileUtil
import com.example.baseutils.LogUtils
import com.example.baseutils.ZipUtils
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadLargeFileListener
import com.liulishuo.filedownloader.FileDownloader
import com.liulishuo.filedownloader.util.FileDownloadUtils
import java.io.File
import kotlin.concurrent.thread

/**
 * Author by lp,on 2022/1/21/021,16:38.
 * 下载视频资源
 */
object DownVideo {
    private val TAG = "DownVideo"
    private val savepath = Constance.VIDE_DIR + "/mirror_detail_video.zip"
    private val downUrl = "https://imagecdn.didano.com/mirrorPlayVideo/mirror_detail_video.zip"
    private  var listtner: DownListtner?=null
    private var downloadTask: BaseDownloadTask? = null
    fun startDown(context: Context, downListtner: DownListtner) {
        this.listtner = downListtner
        listtner?.progress("检查更新")
        if (File(savepath).exists()) {
            listtner?.progress("无需更新", true)
            LogUtils.log(TAG, "已经存在该文件，无需更新下载")
            return
        }
        downloadFile(context)
    }

    fun cancel() {
        downloadTask?.pause()
        listtner=null
    }

    private fun downloadFile(context: Context) {
        FileUtil.deleteDownFile(Constance.VIDE_DIR)
        LogUtils.log(TAG, "downloadFile")
        FileDownloader.setup(context)
        downloadTask = FileDownloader.getImpl().create(downUrl)
            .setPath(savepath)
        downloadTask?.let {
            it.setAutoRetryTimes(2)
                .addHeader("Accept-Encoding", "identity")
                .addHeader(
                    "User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"
                )
                .setListener(object : FileDownloadLargeFileListener() {

                    override fun pending(
                        task: BaseDownloadTask,
                        soFarBytes: Long,
                        totalBytes: Long
                    ) {
                        LogUtils.log(TAG, "----使用FileDownloader下载-------")
                        LogUtils.log(TAG, "pending:soFarBytes($soFarBytes),totalBytes($totalBytes)")
                        if (totalBytes < 0) {
                            it.pause()
                        }
                        listtner?.progress("开始下载")
                    }

                    @SuppressLint("SetTextI18n")
                    override fun progress(
                        task: BaseDownloadTask,
                        soFarBytes: Long,
                        totalBytes: Long
                    ) {
                        if (totalBytes < 0) {
                            it.pause()
                        }
                        var progress = (soFarBytes * 100.0 / totalBytes).toInt()
                        listtner?.progress("下载进度 $progress %")

                    }

                    override fun paused(
                        task: BaseDownloadTask,
                        soFarBytes: Long,
                        totalBytes: Long
                    ) {
                        LogUtils.log(TAG, "获取文件总长度失败出错，尝试HTTPURLConnection下载")
                        listtner?.progress("失败出错,请检查网络")
                        File(savepath).delete()
                        File(FileDownloadUtils.getTempPath(savepath)).delete()
                    }

                    override fun completed(task: BaseDownloadTask) {
                        listtner?.progress("下载完成,解压中")
                        unzip()
                    }

                    override fun error(task: BaseDownloadTask, e: Throwable) {
                        listtner?.progress("下载出错 ${e.printStackTrace()}")
                        LogUtils.log(TAG, "下载出错，尝试HTTPURLConnection下载")

                    }

                    override fun warn(task: BaseDownloadTask) {
                    }
                }).start()
        }


    }

    //解压
    private fun unzip() {
        thread {
            LogUtils.log(TAG, "unzip")
            ZipUtils.unZiFiles(savepath, Constance.VIDE_DIR)
            Handler(Looper.getMainLooper()).post {
                listtner?.progress("解压成功", complete = true)
            }
        }
    }
}